﻿/*******************************************************************
 * 作者：JOHN
 * 类型：添加页面
 * 时间：2011-11-25
 * 说明：
 * ****************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using HZ.Supervise.Model.Enum;
using HZ.Supervise.Model;
using System.Data;
using HZ.Supervise.IBLL;

namespace HZ.Supervise.Web.Secondphase.NewReport
{
    public partial class HospitalStatistics : BasePage
    {
        public HospitalStatistics()
        {
            this.ModuleNo = Module.医院统计分析.ToString();
            this.PageOperateType = OperateType.医院汇总统计.ToString();
        }
        HZ.Supervise.IBLL.IExecuteContext i = HZ.Supervise.BLLFactory.ExecuteContext();
        IBLL_User iu = BLLFactory.BLL_User();
        KeyOperationLogJG kj; 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlArea.InitAreaID = CurrentAccount.GetUser().Org.Area.AreaID;
            }
        }


        public void BindData()
        {
            #region 查询方法

            int t = 0;

            //排序字段
            string orderby = this.OrderFileds.SelectedValue + "  " + this.OrderType.SelectedValue;//排序字段与方式
            HZ.Supervise.Model.SuperviseQuery vs = GetWhere();
            
            #endregion
            System.Data.DataTable dt = i.GetStatistics(1, orderby, vs, this.AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);
            AspNetPager1.RecordCount = t;
            System.Data.DataTable dtSum = i.GetStatistics(1, orderby, vs, 1, 0, out t);

            gvwInfo.PageSize = AspNetPager1.PageSize;
            this.gvwInfo.DataSource = dt;
            this.gvwInfo.DataBind();

            double PurchaseAmountTotal = 0;
            double WareHouseAmountTotal = 0;
            double DistributeAmountTotal = 0;
            double ComResonseAmount = 0;
            for (int j = 0; j < dtSum.Rows.Count; j++)
            { 
                PurchaseAmountTotal += Convert.ToDouble(dtSum.Rows[j]["PurchaseAmount"]);
                ComResonseAmount += Convert.ToDouble(dtSum.Rows[j]["ComResonseAmount"]);
                WareHouseAmountTotal += Convert.ToDouble(dtSum.Rows[j]["WarehouseAmount"]);
                DistributeAmountTotal += Convert.ToDouble(dtSum.Rows[j]["DistributeAmount"]);
            }

            this.lblCount.Text = "采购总金额为：" + PurchaseAmountTotal.ToString("0.00") + "元;" + "企业响应总金额为：" + ComResonseAmount.ToString("0.00") + "元;" + "配送总金额：" + DistributeAmountTotal.ToString("0.00") + "元;" + "入库总金额：" + WareHouseAmountTotal.ToString("0.00") + "元;";
            AddLog(string.Format("查询医疗机构汇总统计数据!"));
        }

        /// <summary>
        /// 翻页显示
        /// </summary>
        /// <param name="sender">事件发送源</param>
        /// <param name="e">事件参数</param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BindData();
        }


        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="sender">事件发送源</param>
        /// <param name="e">事件参数</param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
        }

        private DataTable getDataExcel()
        {
            int t = 0;
            HZ.Supervise.Model.SuperviseQuery vs = GetWhere();
            //排序字段
            string orderby = this.OrderFileds.SelectedValue + "  " + this.OrderType.SelectedValue;//排序字段与方式
            System.Data.DataTable dt = i.GetStatistics(1,  orderby,vs , 1, 0, out t);
            return dt;
        }

        private HZ.Supervise.Model.SuperviseQuery GetWhere()
        {
            HZ.Supervise.Model.SuperviseQuery vs = new SuperviseQuery();
            vs.Append += string.Format(" 1=1 ");
			DateTime startime;
			DateTime endtime;
			if (!string.IsNullOrEmpty(txtStratTime.Text.Trim()))
			{
				startime = (DateTime)new HZ.Common.ConvertHelper(txtStratTime.Text.Trim()).ToDateTime;//开始时间
				vs.Append += string.Format(" and SubmiTime>= '{0}'", startime);
			}
			if (!string.IsNullOrEmpty(txtEndTime.Text.Trim()))
			{
                endtime = (DateTime)new HZ.Common.ConvertHelper(txtEndTime.Text.Trim()).ToDateTime;//结束时间
                if (endtime >= Convert.ToDateTime(txtStratTime.Text.Trim()))
                {
                    endtime = endtime.AddDays(1).AddMilliseconds(-1);
                    vs.Append += string.Format(" and SubmiTime <= '{0}' ", endtime);
                }
                else
                {
                    HZ.Web.WebUtil.Alert("截止时间不能小于起始时间");
                }
			}

            vs.AreaID = ddlArea.SelectedAreaID;
            //医院名称
            if (!string.IsNullOrEmpty(txtHospital.Text))
            {
                vs.HospitalName = this.txtHospital.Text.Trim();
            }
            else
            {
                vs.HospitalName = null;
            }
            User u = iu.GetUserByUserID(CurrentAccount.GetUser().UserID);
            if (u.IsJK == true)
            {
                vs.Append += string.Format(" and HospitalID like 'jk%'");
            }

            return vs;

        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="sender">事件发送源</param>
        /// <param name="e">事件参数</param>
        protected void btnExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = getDataExcel();
            if (dt.Rows.Count <= 0)
            {
                HZ.Web.WebUtil.Alert("没有需要导出的数据！", this);
            }
            else
            {
                AddLog(string.Format("导出医疗机构汇总统计数据成功!"));
                //HZ.Excel.ExcelHelper.ExportDataForWeb(dt, gvwInfo);
                ExportFile.Instance.ExportData(dt, gvwInfo, this.Page); 
            }
        }

        protected void gvwInfo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            Control cmdControl = e.CommandSource as Control;
            GridViewRow row = cmdControl.NamingContainer as GridViewRow;
            LinkButton lbnR = (LinkButton)row.FindControl("lbnP");
            string str = lbnR.CommandArgument;
            if (str != "total")
            {
                string sessionId = Guid.NewGuid().ToString();
                SuperviseQuery vs = GetWhere();

                vs.HospitalID = str.Split('|')[0];
                vs.HospitalName = str.Split('|')[1];
                vs.BackPage = "hospital";

                Session[sessionId] = vs;

                if (e.CommandName == "lbnP")
                {
                   
                    Response.Redirect(string.Format("../../Enterprise/PurchaseAmountDetail.aspx?sesid={0}", sessionId));
                }
                if (e.CommandName == "lbnCR")
                {

                    Response.Redirect(string.Format("../../Enterprise/ComResonseAmountDetail.aspx?sesid={0}", sessionId));
                }
                if (e.CommandName == "lbnD")
                {

                    Response.Redirect(string.Format("../../Enterprise/DistributeAmountDetail.aspx?sesid={0}", sessionId));
                }
                if (e.CommandName == "lbnW")
                {
                    Response.Redirect(string.Format("../../Enterprise/WarehouseAmountDetail.aspx?sesid={0}", sessionId));
                }
                if (e.CommandName == "lbnS")
                {
                    Response.Redirect(string.Format("../../Enterprise/SellAmountDetail.aspx?sesid={0}", sessionId));
                }
                //if (e.CommandName == "lbnR")
                //{
                //    Response.Redirect(string.Format("../../Enterprise/ReturnAmountDetail.aspx?sesid={0}", sessionId));
                //}
                if (e.CommandName == "lbnC")
                {
                    Response.Redirect(string.Format("../../Enterprise/StockAmountDetail.aspx?sesid={0}", sessionId));
                }
            }

        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            string sesid = Guid.NewGuid().ToString ();
            DataTable dt = getDataExcel();
            Session[sesid] =  dt; 
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>window.open('PrintHosStatistics.aspx?sesid=" + sesid + "');</script>");

        } 
        protected void btnPrintBook_Click(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>window.open('../Print/Default.aspx');</script>");
        }
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="msg"></param>
        private void AddLog(string msg)
        {
            kj = new KeyOperationLogJG();
            kj.OperationLogSerialID = Guid.NewGuid().ToString();
            kj.Operator = CurrentAccount.GetUser().UserID;
            kj.OrgID = CurrentAccount.GetUser().Org.OrgID;
            kj.OperateTime = DateTime.Now;
            kj.OperateMessage = msg;
            iu.AddKeyOperationLog(kj);
        }
    }
}
